using System;
using UnityEngine;

namespace M13.Game.World
{
    public class Chunk : IChunkReference
    {
        public Vector2Int ChunkLocalCoord { get; private set; }

        //δ��ѹ����ԭʼ����
        public byte[] ContinentalValueMap { get; private set; }
        public byte[] ChunkHeightMap { get; private set; }
        public byte[] ChunkTurfIdMap { get; private set; }
        

        private int _ctimLength;

        public Chunk() { }
        public Chunk(Vector2Int chunkLocalCoord)
        {
            _ctimLength = WorldConstant.ChunkSideLength ^ 2 * (int)(WorldConstant.MaxTurfHeightNumber / WorldConstant.TurfHeight);
            this.ChunkLocalCoord = chunkLocalCoord;
            ChunkHeightMap = new byte[WorldConstant.ChunkSideLength ^ 2];
            ChunkTurfIdMap = new byte[_ctimLength];
            ContinentalValueMap = new byte[WorldConstant.ChunkSideLength ^ 2];
        }

        /// <summary>
        /// �����ó�����������ʱҪ�����Խ��и�ֵ
        /// </summary>
        /// <param name="chunkLocalCoord"></param>
        /// <param name="chunkHeightMap"></param>
        /// <param name="chunkTurfIdMap"></param>
        public void Init(Vector2Int chunkLocalCoord, byte[] continentalValueMap, byte[] chunkHeightMap, byte[] chunkTurfIdMap)
        {
            this.ChunkLocalCoord = chunkLocalCoord;
            this.ChunkHeightMap = chunkHeightMap;
            this.ChunkTurfIdMap = chunkTurfIdMap;
            this.ContinentalValueMap = continentalValueMap;
        }

        /// <summary>
        /// ����Chunk����ʱ��������Ե�ֵ
        /// </summary>
        public void ClearChunkData() 
        {
            ChunkLocalCoord = Vector2Int.zero;
            Array.Clear(ChunkHeightMap, 0, ChunkHeightMap.Length);
            Array.Clear(ChunkTurfIdMap, 0, ChunkTurfIdMap.Length);
            Array.Clear(ContinentalValueMap, 0, ContinentalValueMap.Length);
        }



        private int GetIndexInHmByPos(Vector2Int pos)
        {
            if (pos.x > 15 || pos.y > 15) Debug.LogError("���곬�����鷶Χ");
            return ((pos.y << 4) + pos.x);
        }
        private Vector2Int GetPosInHmByIndex(int index)
        {
            if (index > 255) Debug.LogError("�����������ݳ���");
            int y = index >> 4;
            int x = index - y;
            return new Vector2Int(index % 16, index >> 4);
        }
        private int GetIndexOfTimByPos(Vector3 pos)
        {
            if (pos.x > 15 || pos.z > 15 || pos.y > 15) Debug.LogError("���곬�����鷶Χ");
            return (int)pos.x + ((int)pos.z << 4) + ((int)pos.y * 2 << 8);
        }
        private Vector3 GetPosInTimByIndex(int index)
        {
            if (index > 8192) Debug.LogError("�����������ݳ���");
            int y = index >> 8;
            int z = (index - (y << 8)) >> 4;
            int x = index - (y << 8) - (z << 4);
            return new Vector3(x, y / 2f, z);
        }
    }
} 
